const app = getApp();
var url = app.data.url;
var picRoot = app.data.picRoot;
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
var util = require('../../utils/util.js');

var date = util.formatDate(new Date().getTime());
var time = util.formatTime(new Date().getTime());
Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderType: 'IN_HALL', //默认堂食
    inHallDot: true,
    takeOutDot: false,
    takeOutPopupShow: false,
    displayDate: date,
    displayTime: time,
    showDate: false,
    showTime: false,
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    takeOutInfoShow: false,
    takeOutDateTime: '',
    isShareByJielong: '',
    jielongPhone: '',
    jielongAddress: '',
    jielongId: '',
    jielongPayOrderId: '',
    minHour: 10,
    maxHour: 20,
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return `${value}日`;
    },
    time: '',
    deskInfo: '',
    orderNo: '',
    itemInfo: '',
    orderId: '',
    itemInfoList: [],
    deskInfoList: [],
    order_mark: "请填写订单备注 (偏好、口味)",
    relation_mark: "请填写联系方式",
    totalPrice: 0,
    modelId: 'jY9ixz8CDDdFSpeOuYqS4hlQzG7wo5K_YpVxU88bCf0',
    template_model_id: '0BnoZDpPF4Khi8MY55xCxba74yd3nhG5mK2CmnhRzKE',
    queryType: '',
    downOrderTime: '',
    uuid: app.globalData.openId,
    show: false,
    relationName: '',
    relationPhone: '',
    list8: [],
    list9: [],
    list10: [],
    list11: [],
    list12: [],
    roomPic: [],
    roomName: '',
    roomDesc: '',
    roomNum: '',
    payType: '',
    merchantId: '',
    jsonData: '',
    mark: '',
    differDay: 0,
    peopleNum: 0,
    inHallPreMenu: '',
    disabledStatus: false,
    payonline: 'N',
    tableFee:0,
    totalTableFee: 0,
    depositRate: 0
  },
  onMarkChange(event) {
    let _that = this;
    _that.setData({
      mark: event.detail
    })
  },
  closeRoomDetail: function (option) {
    let _that = this;
    _that.setData({
      roomDetailShow: false
    })
  },

  /***
   * 自动接单
   */
  autoAccept: function(orderId, orderType){
    let _that = this;
    let merchantId = _that.data.merchantId;
    wx.request({
      url: url + '/OrderApi/checkAutoAccept',
      data: {
        merchantId: merchantId,
        orderType: orderType
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.code == 200) {
          // 自动接单
          wx.request({
            url: url + '/PrintApi/print',
            data: {
              orderId: orderId,
              merchantId: merchantId
            },
            method: 'POST',
            header: {
              'content-type': 'application/json'
            },
            success: function (e) {
              console.log("自动接单");
            }
          })
        }
      }
    })

  },


  onSubmit: function (options) {
    let _that = this;
    //点击支付,禁用按钮,防止多次点击
    _that.setData({
      disabledStatus: true
    })
    // let orderId = _that.data.orderNo;
    let wxUserUuid = app.globalData.openId;
    let relationName = _that.data.relationName;
    let relationPhone = _that.data.relationPhone;
    let merchantId = _that.data.merchantId;
    let jsonData = _that.data.jsonData;
    let orderType = _that.data.orderType;
    let mark = _that.data.mark;
    let queryType = _that.data.queryType;
    let inHallPreMenu = _that.data.inHallPreMenu;
    let payonline = _that.data.payonline;
    let takeOutDateTime = _that.data.takeOutDateTime; //自提时间
    jsonData.mark = mark;
    if (_that.data.takeOutDateTime){
      jsonData.timeVal = _that.data.takeOutDateTime;
    }
    jsonData.takeOutDateTime = takeOutDateTime;
    jsonData.relationName = relationName;
    jsonData.relationPhone = relationPhone;
    jsonData.totalPrice = _that.data.totalPrice / 100;
    if (!jsonData.token) {
      jsonData.token = _that.data.uuid;
    }
    jsonData.orderType = orderType;
    jsonData.queryType = queryType;
    jsonData.isShareByJielong = _that.data.isShareByJielong;
    jsonData.jielongId = _that.data.jielongId;
    jsonData.jielongPayOrderId = _that.data.jielongPayOrderId;
    console.log("jsonData");
    console.log(jsonData);
    
    /*if (orderType == 'SUBSCRIBE_IN_HALL' && inHallPreMenu == 1) {
      // 预定餐桌, 点餐, 支付需带上茶位费, 定金比例
      let tableFeeJson = {};
      let tableFee = _that.data.tableFee;
      let peopleNum = _that.data.peopleNum;
      let totalTableFee = _that.data.totalTableFee;
      let depositRate = _that.data.depositRate;
      tableFeeJson.tableFee = tableFee;
      tableFeeJson.peopleNum = peopleNum;
      tableFeeJson.depositRate = depositRate;
      tableFeeJson.totalTableFee = totalTableFee;
      jsonData.tableFeeJson = JSON.stringify(tableFeeJson);
    }*/
    // 更新联系人姓名/手机
    // 先新增订单
    if (queryType == 0) {
      /*if (orderType == 'SUBSCRIBE_IN_HALL' && inHallPreMenu == 0) {
        // 单纯订桌子的情况, 无需支付, 只新增订单
        wx.request({
          url: url + '/OrderApi/insertOrder',
          data: jsonData,
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            if (res.data.code == 200) {
              let orderId = res.data.data;
              // 支付成功, 发送消息
              wx.requestSubscribeMessage({
                tmplIds: [_that.data.modelId, _that.data.template_model_id],
                success(res) {
                  // 是否自动接单
                  _that.autoAccept(orderId, orderType);
                  wx.request({
                    url: url + '/WeChatPayApi/toSendMessage',
                    data: {
                      orderId: orderId,
                      wxUserUuid: wxUserUuid
                    },
                    method: 'POST',
                    header: {
                      'content-type': 'application/x-www-form-urlencoded'
                    },
                    success: function (e) {
                      console.log("发送订阅消息:");
                      console.log(e);
                    }
                  })
                  // 发送模板消息
                  wx.request({
                    url: url + '/WeChatPayApi/sendModelMms',
                    data: {
                      orderId: orderId,
                      wxUserUuid: wxUserUuid
                    },
                    method: 'POST',
                    header: {
                      'content-type': 'application/x-www-form-urlencoded'
                    },
                    success: function (res) {
                      console.log("发送模板消息:");
                      console.log(res);
                    }
                  })
                  // 跳转订单支付成功页面
                  wx.reLaunch({
                    url: '../../pages/pay-detail/index?orderId=' + orderId + "&queryType=" + _that.data.queryType,
                  })
                }
              })



            } else if (res.data.code == 500) {
              // 登录
              // 尚未登录
              Dialog.confirm({
                title: '提示',
                message: '您当前尚未登录, 请点击确认跳转登录页面!'
              }).then(() => {
                // on confirm
                wx.navigateTo({
                  url: "../../pages/login/index"
                })
              }).catch(() => {
                // on cancel
              });
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: "none",
                duration: 2000
              })
            }
          }
        })
      } else if (orderType == 'IN_HALL' && payonline == 'N') {
        // 堂食且在线支付开关关闭的情况系，无需支付， 只新增订单
        wx.request({
          url: url + '/OrderApi/insertOrder',
          data: jsonData,
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            if (res.data.code == 200) {
              let orderId = res.data.data;
              // 支付成功, 发送消息
              wx.requestSubscribeMessage({
                tmplIds: [_that.data.modelId, _that.data.template_model_id],
                success(res) {
                  // 是否自动接单
                  _that.autoAccept(orderId, orderType);
                  wx.request({
                    url: url + '/WeChatPayApi/toSendMessage',
                    data: {
                      orderId: orderId,
                      wxUserUuid: wxUserUuid
                    },
                    method: 'POST',
                    header: {
                      'content-type': 'application/x-www-form-urlencoded'
                    },
                    success: function (e) {
                      console.log("发送订阅消息:");
                      console.log(e);
                    }
                  })
                  // 发送模板消息
                  wx.request({
                    url: url + '/WeChatPayApi/sendModelMms',
                    data: {
                      orderId: orderId,
                      wxUserUuid: wxUserUuid
                    },
                    method: 'POST',
                    header: {
                      'content-type': 'application/x-www-form-urlencoded'
                    },
                    success: function (res) {
                      console.log("发送模板消息:");
                      console.log(res);
                    }
                  })
                  // 跳转订单支付成功页面
                  wx.reLaunch({
                    url: '../../pages/pay-detail/index?orderId=' + orderId + "&queryType=" + _that.data.queryType,
                  })
                }
              })
            } else if (res.data.code == 500) {
              // 登录
              // 尚未登录
              Dialog.confirm({
                title: '提示',
                message: '您当前尚未登录, 请点击确认跳转登录页面!'
              }).then(() => {
                // on confirm
                wx.navigateTo({
                  url: "../../pages/login/index"
                })
              }).catch(() => {
                // on cancel
              });
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: "none",
                duration: 2000
              })
            }
          }
        })
      } else { */
        wx.request({
          url: url + '/OrderApi/insertOrder',
          data: jsonData,
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            let orderId = res.data.data;
            if (res.data.code == 200) {
              //只有堂食才可以选择是否在线支付(即是否一定通过平台支付)
              /*if (orderType == 'IN_HALL') {
                wx.requestSubscribeMessage({
                  tmplIds: [_that.data.modelId, _that.data.template_model_id],
                  success(res) {
                    wx.request({
                      url: url + '/WeChatPayApi/servicePrePay',
                      data: {
                        uuid: wxUserUuid,
                        orderId: orderId,
                        merchantId: merchantId
                      },
                      method: 'POST',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      success: function (res) {
                        if (res.data.code == 200) {
                          // 发起支付
                          let item = res.data.data;
                          let wxPaymentPojo = item.wxPaymentParamPojo;
                          wx.requestPayment({
                            'timeStamp': wxPaymentPojo.timeStamp,
                            'nonceStr': wxPaymentPojo.nonceStr,
                            'package': wxPaymentPojo.packageStr,
                            'signType': 'MD5',
                            'paySign': wxPaymentPojo.paySign,
                            'success': function (res) {
                              // 是否自动接单
                              _that.autoAccept(orderId, orderType);
                              // 支付成功, 更新订单状态
                              let jsonParam = JSON.stringify(item.stringStringMap);
                              wx.request({
                                url: url + '/WeChatPayApi/insertWxPay',
                                data: {
                                  jsonParam: jsonParam
                                },
                                method: 'POST',
                                header: {
                                  'content-type': 'application/x-www-form-urlencoded'
                                },
                                success: function (res) {
                                  if (res.data.code == 200) {
                                    wx.request({
                                      url: url + '/WeChatPayApi/updatePreOrderStatusByOrderId',
                                      data: {
                                        orderId: orderId
                                      },
                                      method: 'POST',
                                      header: {
                                        'content-type': 'application/x-www-form-urlencoded'
                                      },
                                      success: function (res) {
                                        if (res.data.code == 200) {
                                          // 支付成功, 发送消息
                                          wx.request({
                                            url: url + '/WeChatPayApi/toSendMessage',
                                            data: {
                                              orderId: orderId,
                                              wxUserUuid: wxUserUuid
                                            },
                                            method: 'POST',
                                            header: {
                                              'content-type': 'application/x-www-form-urlencoded'
                                            },
                                            success: function (res) {
                                              console.log("发送订阅消息:" + res);
                                            }
                                          })

                                          // 发送模板消息
                                          wx.request({
                                            url: url + '/WeChatPayApi/sendModelMms',
                                            data: {
                                              orderId: orderId,
                                              wxUserUuid: wxUserUuid
                                            },
                                            method: 'POST',
                                            header: {
                                              'content-type': 'application/x-www-form-urlencoded'
                                            },
                                            success: function (res) {
                                              console.log("发送模板消息:" + res);
                                            }
                                          })

                                          // 跳转订单支付成功页面
                                          wx.reLaunch({
                                            url: '../../pages/pay-detail/index?orderId=' + orderId + "&queryType=" + _that.data.queryType,
                                          })
                                        } else {
                                          wx.showToast({
                                            title: res.data.msg,
                                            icon: "none",
                                            duration: 2000
                                          })
                                        }
                                      }
                                    })

                                  } else {
                                    wx.showToast({
                                      title: res.data.msg,
                                      icon: "none",
                                      duration: 2000
                                    })
                                  }
                                }
                              })

                            },
                            'fail': function (res) {
                              console.log("支付失败!");
                              console.log(res);
                            },
                            'complete': function (res) {
                              console.log("方法调用结束");
                              console.log(res);
                            }
                          })
                        } else {
                          wx.showToast({
                            title: res.data.msg,
                            icon: "none",
                            duration: 2000
                          })
                        }

                      },
                      fail: function (res) {
                        console.info('submit fail');
                      },
                      complete: function (res) {
                        console.info('submit complete');
                      }
                    })
                  }
                })
              } else { */
                wx.request({
                  url: url + '/OrderApi/updateNameAndPhoneByOrderId',
                  data: {
                    orderId: orderId,
                    name: relationName,
                    phone: relationPhone,
                    isShareByJielong: jsonData.isShareByJielong
                  },
                  method: 'POST',
                  header: {
                    'content-type': 'application/x-www-form-urlencoded'
                  },
                  success: function (res) {
                    console.log("发起支付1");
                    if (res.data.code == 200) {
                      // 发起支付
                      console.log("发起支付2");
                      console.log(wxUserUuid);
                      console.log(orderId);
                      console.log(merchantId);
                      wx.requestSubscribeMessage({
                        tmplIds: [_that.data.modelId, _that.data.template_model_id],
                        success(res) {
                          wx.request({
                            url: url + '/WeChatPayApi/servicePrePay',
                            data: {
                              uuid: wxUserUuid,
                              orderId: orderId,
                              merchantId: merchantId,
                              isShareByJielong:_that.data.isShareByJielong,
                              jielongPayOrderId: _that.data.jielongPayOrderId
                            },
                            method: 'POST',
                            header: {
                              'content-type': 'application/x-www-form-urlencoded'
                            },
                            success: function (res) {
                              console.log("发起支付3");
                              console.log(res.data.code);
                              if (res.data.code == 200) {
                                // 发起支付
                                let item = res.data.data;
                                let wxPaymentPojo = item.wxPaymentParamPojo;
                                console.log(wxPaymentPojo);
                                wx.requestPayment({
                                  'timeStamp': wxPaymentPojo.timeStamp,
                                  'nonceStr': wxPaymentPojo.nonceStr,
                                  'package': wxPaymentPojo.packageStr,
                                  'signType': 'MD5',
                                  'paySign': wxPaymentPojo.paySign,
                                  'success': function (res) {
                                    console.log("发起支付4");
                                    console.log(res);
                                    // 是否自动接单
                                    _that.autoAccept(orderId, orderType);
                                    // 支付成功, 更新订单状态
                                    let jsonParam = JSON.stringify(item.stringStringMap);
                                    
                                    wx.request({
                                      url: url + '/WeChatPayApi/insertWxPay',
                                      data: {
                                        jsonParam: jsonParam
                                      },
                                      method: 'POST',
                                      header: {
                                        'content-type': 'application/x-www-form-urlencoded'
                                      },
                                      success: function (res) {
                                        console.log("发起支付5");
                                        if (res.data.code == 200) {
                                          wx.request({
                                            url: url + '/WeChatPayApi/updatePreOrderStatusByOrderId',
                                            data: {
                                              orderId: orderId
                                            },
                                            method: 'POST',
                                            header: {
                                              'content-type': 'application/x-www-form-urlencoded'
                                            },
                                            success: function (res) {
                                              console.log("发起支付6");
                                              if (res.data.code == 200) {
                                                // 支付成功, 发送消息
                                                wx.request({
                                                  url: url + '/WeChatPayApi/toSendMessage',
                                                  data: {
                                                    orderId: orderId,
                                                    wxUserUuid: wxUserUuid
                                                  },
                                                  method: 'POST',
                                                  header: {
                                                    'content-type': 'application/x-www-form-urlencoded'
                                                  },
                                                  success: function (res) {
                                                    console.log("发送订阅消息:" + res);
                                                  }
                                                })

                                                // 发送模板消息
                                                wx.request({
                                                  url: url + '/WeChatPayApi/sendModelMms',
                                                  data: {
                                                    orderId: orderId,
                                                    wxUserUuid: wxUserUuid
                                                  },
                                                  method: 'POST',
                                                  header: {
                                                    'content-type': 'application/x-www-form-urlencoded'
                                                  },
                                                  success: function (res) {
                                                    console.log("发送模板消息:" + res);
                                                  }
                                                })
                                                  
                                                 
                                                // 跳转订单支付成功页面
                                                wx.reLaunch({
                                                  url: '../../pages/pay-detail/index?orderId=' + orderId + "&queryType=" + _that.data.queryType + "&isShareByJielong=" + _that.data.isShareByJielong + "&jielongPayOrderId=" + _that.data.jielongPayOrderId
                                                })
                                              } else {
                                                wx.showToast({
                                                  title: res.data.msg,
                                                  icon: "none",
                                                  duration: 2000
                                                })
                                              }
                                            }
                                          })

                                        } else {
                                          wx.showToast({
                                            title: res.data.msg,
                                            icon: "none",
                                            duration: 2000
                                          })
                                        }
                                      }
                                    })

                                  },
                                  'fail': function (res) {
                                    console.log("支付失败!");
                                    console.log(res);
                                  },
                                  'complete': function (res) {
                                    console.log("方法调用结束");
                                    console.log(res);
                                  }
                                })
                              } else {
                                wx.showToast({
                                  //title: res.data.msg,
                                  title: '什么情况',
                                  icon: "none",
                                  duration: 2000
                                })
                              }

                            },
                            fail: function (res) {
                              console.info('submit fail');
                            },
                            complete: function (res) {
                              console.info('submit complete');
                            }
                          })
                        }
                      })
                    } else {
                      wx.showToast({
                        title: res.data.msg,
                        icon: "none",
                        duration: 2000
                      })
                    }
                  },
                  fail: function (res) {
                    console.info('submit fail');
                  },
                  complete: function (res) {
                    console.info('submit complete');
                  }
                })
              /*}*/

            } else if (res.data.code == 500) {
              //尚未登录
              Dialog.confirm({
                title: '提示',
                message: '您当前尚未登录, 请点击确认跳转登录页面!'
              }).then(() => {
                // on confirm
                wx.navigateTo({
                  url: "../../pages/login/index"
                })
              }).catch(() => {
                // on cancel
              });
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: "none",
                duration: 2000
              })
            }

          },
          fail: function (res) {
            console.info('submit fail');
          },
          complete: function (res) {
            console.info('submit complete');
          }

        })
      /*}*/


    } else if (queryType == 1) {
      wx.request({
        url: url + '/OrderApi/insertOrderForHotel',
        data: jsonData,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          let orderId = res.data.data;
          if (res.data.code == 200) {
            wx.request({
              url: url + '/OrderApi/updateNameAndPhoneByOrderId',
              data: {
                orderId: orderId,
                name: relationName,
                phone: relationPhone
              },
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                if (res.data.code == 200) {
                  // 发起支付
                  console.log("发起支付");
                  wx.requestSubscribeMessage({
                    tmplIds: [_that.data.modelId, _that.data.template_model_id],
                    success(res) {
                      wx.request({
                        url: url + '/WeChatPayApi/servicePrePay',
                        data: {
                          uuid: wxUserUuid,
                          orderId: orderId,
                          merchantId: merchantId
                        },
                        method: 'POST',
                        header: {
                          'content-type': 'application/x-www-form-urlencoded'
                        },
                        success: function (res) {
                          if (res.data.code == 200) {
                            // 发起支付
                            let item = res.data.data;
                            let wxPaymentPojo = item.wxPaymentParamPojo;
                            wx.requestPayment({
                              'timeStamp': wxPaymentPojo.timeStamp,
                              'nonceStr': wxPaymentPojo.nonceStr,
                              'package': wxPaymentPojo.packageStr,
                              'signType': 'MD5',
                              'paySign': wxPaymentPojo.paySign,
                              'success': function (res) {
                                // 支付成功, 更新订单状态
                                let jsonParam = JSON.stringify(item.stringStringMap);
                                wx.request({
                                  url: url + '/WeChatPayApi/insertWxPay',
                                  data: {
                                    jsonParam: jsonParam
                                  },
                                  method: 'POST',
                                  header: {
                                    'content-type': 'application/x-www-form-urlencoded'
                                  },
                                  success: function (res) {
                                    if (res.data.code == 200) {
                                      wx.request({
                                        url: url + '/WeChatPayApi/updatePreOrderStatusByOrderId',
                                        data: {
                                          orderId: orderId
                                        },
                                        method: 'POST',
                                        header: {
                                          'content-type': 'application/x-www-form-urlencoded'
                                        },
                                        success: function (res) {
                                          if (res.data.code == 200) {
                                            // 支付成功, 发送消息
                                            wx.request({
                                              url: url + '/WeChatPayApi/toSendMessage',
                                              data: {
                                                orderId: orderId,
                                                wxUserUuid: wxUserUuid
                                              },
                                              method: 'POST',
                                              header: {
                                                'content-type': 'application/x-www-form-urlencoded'
                                              },
                                              success: function (res) {
                                                console.log("发送订阅消息:" + res);
                                              }
                                            })

                                            // 发送模板消息
                                            wx.request({
                                              url: url + '/WeChatPayApi/sendModelMms',
                                              data: {
                                                orderId: orderId,
                                                wxUserUuid: wxUserUuid
                                              },
                                              method: 'POST',
                                              header: {
                                                'content-type': 'application/x-www-form-urlencoded'
                                              },
                                              success: function (res) {
                                                console.log("发送模板消息:" + res);
                                              }
                                            })

                                            // 跳转订单支付成功页面
                                            wx.reLaunch({
                                              url: '../../pages/pay-detail/index?orderId=' + orderId + "&queryType=" + _that.data.queryType,
                                            })
                                          } else {
                                            wx.showToast({
                                              title: res.data.msg,
                                              icon: "none",
                                              duration: 2000
                                            })
                                          }
                                        }
                                      })

                                    } else {
                                      wx.showToast({
                                        title: res.data.msg,
                                        icon: "none",
                                        duration: 2000
                                      })
                                    }
                                  }
                                })

                              },
                              'fail': function (res) {
                                console.log("支付失败!");
                                console.log(res);
                              },
                              'complete': function (res) {
                                console.log("方法调用结束");
                                console.log(res);
                              }
                            })
                          } else {
                            wx.showToast({
                              title: res.data.msg,
                              icon: "none",
                              duration: 2000
                            })
                          }

                        },
                        fail: function (res) {
                          console.info('submit fail');
                        },
                        complete: function (res) {
                          console.info('submit complete');
                        }
                      })
                    }
                  })
                } else {
                  wx.showToast({
                    title: res.data.msg,
                    icon: "none",
                    duration: 2000
                  })
                }
              },
              fail: function (res) {
                console.info('submit fail');
              },
              complete: function (res) {
                console.info('submit complete');
              }
            })
          } else if (res.data.code == 500) {
            // 尚未登录
            Dialog.confirm({
              title: '提示',
              message: '您当前尚未登录, 请点击确认跳转登录页面!'
            }).then(() => {
              // on confirm
              wx.navigateTo({
                url: "../../pages/login/index"
              })
            }).catch(() => {
              // on cancel
            });
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000
            })
          }
        },
        fail: function (res) {
          console.info('submit fail');
        },
        complete: function (res) {
          console.info('submit complete');
        }
      })
    } else if (queryType == 2) {
      wx.request({
        url: url + '/OrderApi/insertOrderForScenic',
        data: jsonData,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          let orderId = res.data.data;
          if (res.data.code == 200) {
            wx.request({
              url: url + '/OrderApi/updateNameAndPhoneByOrderId',
              data: {
                orderId: orderId,
                name: relationName,
                phone: relationPhone
              },
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                if (res.data.code == 200) {
                  // 发起支付
                  console.log("发起支付");
                  wx.requestSubscribeMessage({
                    tmplIds: [_that.data.modelId, _that.data.template_model_id],
                    success(res) {
                      wx.request({
                        url: url + '/WeChatPayApi/servicePrePay',
                        data: {
                          uuid: wxUserUuid,
                          orderId: orderId,
                          merchantId: merchantId
                        },
                        method: 'POST',
                        header: {
                          'content-type': 'application/x-www-form-urlencoded'
                        },
                        success: function (res) {
                          if (res.data.code == 200) {
                            // 发起支付
                            let item = res.data.data;
                            let wxPaymentPojo = item.wxPaymentParamPojo;
                            wx.requestPayment({
                              'timeStamp': wxPaymentPojo.timeStamp,
                              'nonceStr': wxPaymentPojo.nonceStr,
                              'package': wxPaymentPojo.packageStr,
                              'signType': 'MD5',
                              'paySign': wxPaymentPojo.paySign,
                              'success': function (res) {
                                // 支付成功, 更新订单状态
                                let jsonParam = JSON.stringify(item.stringStringMap);
                                wx.request({
                                  url: url + '/WeChatPayApi/insertWxPay',
                                  data: {
                                    jsonParam: jsonParam
                                  },
                                  method: 'POST',
                                  header: {
                                    'content-type': 'application/x-www-form-urlencoded'
                                  },
                                  success: function (res) {
                                    if (res.data.code == 200) {
                                      wx.request({
                                        url: url + '/WeChatPayApi/updatePreOrderStatusByOrderId',
                                        data: {
                                          orderId: orderId
                                        },
                                        method: 'POST',
                                        header: {
                                          'content-type': 'application/x-www-form-urlencoded'
                                        },
                                        success: function (res) {
                                          if (res.data.code == 200) {
                                            // 支付成功, 发送消息
                                            wx.request({
                                              url: url + '/WeChatPayApi/toSendMessage',
                                              data: {
                                                orderId: orderId,
                                                wxUserUuid: wxUserUuid
                                              },
                                              method: 'POST',
                                              header: {
                                                'content-type': 'application/x-www-form-urlencoded'
                                              },
                                              success: function (res) {
                                                console.log("发送订阅消息:" + res);
                                              }
                                            })

                                            // 发送模板消息
                                            wx.request({
                                              url: url + '/WeChatPayApi/sendModelMms',
                                              data: {
                                                orderId: orderId,
                                                wxUserUuid: wxUserUuid
                                              },
                                              method: 'POST',
                                              header: {
                                                'content-type': 'application/x-www-form-urlencoded'
                                              },
                                              success: function (res) {
                                                console.log("发送模板消息:" + res);
                                              }
                                            })

                                            // 跳转订单支付成功页面
                                            wx.reLaunch({
                                              url: '../../pages/pay-detail/index?orderId=' + orderId + "&queryType=" + _that.data.queryType,
                                            })
                                          } else {
                                            wx.showToast({
                                              title: res.data.msg,
                                              icon: "none",
                                              duration: 2000
                                            })
                                          }
                                        }
                                      })

                                    } else {
                                      wx.showToast({
                                        title: res.data.msg,
                                        icon: "none",
                                        duration: 2000
                                      })
                                    }
                                  }
                                })

                              },
                              'fail': function (res) {
                                console.log("支付失败!");
                                console.log(res);
                              },
                              'complete': function (res) {
                                console.log("方法调用结束");
                                console.log(res);
                              }
                            })
                          } else {
                            wx.showToast({
                              title: res.data.msg,
                              icon: "none",
                              duration: 2000
                            })
                          }

                        },
                        fail: function (res) {
                          console.info('submit fail');
                        },
                        complete: function (res) {
                          console.info('submit complete');
                        }
                      })
                    }
                  })
                } else {
                  wx.showToast({
                    title: res.data.msg,
                    icon: "none",
                    duration: 2000
                  })
                }
              },
              fail: function (res) {
                console.info('submit fail');
              },
              complete: function (res) {
                console.info('submit complete');
              }
            })
          } else if (res.data.code == 500) {
            // 尚未登录
            Dialog.confirm({
              title: '提示',
              message: '您当前尚未登录, 请点击确认跳转登录页面!'
            }).then(() => {
              // on confirm
              wx.navigateTo({
                url: "../../pages/login/index"
              })
            }).catch(() => {
              // on cancel
            });
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000
            })
          }
        },
        fail: function (res) {
          console.info('submit fail');
        },
        complete: function (res) {
          console.info('submit complete');
        }
      })
    }




  },
  /**
   * 禁止滚动穿透
   */
  touchMove: function () {

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      disabledStatus: false,
      isShareByJielong: options.isShareByJielong,
      jielongId: options.jielongId,
      jielongPhone: options.jielongPhone,
      jielongAddress: options.jielongAddress,
      jielongPayOrderId: options.jielongPayOrderId
    })
    console.log(options);
    let jsonData = JSON.parse(options.tempData);
    // 设置插入订单数据
    console.log(jsonData);
    that.setData({
      jsonData: jsonData
    })
    let cart = JSON.parse(jsonData.itemApi);
    console.log(cart);
    var queryType = options.queryType;
    var merchantId = options.merchantId;
    var inHallPreMenu = jsonData.inHallPreMenu;
    //var orderType = jsonData.orderType;
   
    //计算订单每一个菜的总金额与所有菜合计金额
    let totalPrice = 0
    for (var i = 0; i < cart.length; i++) {
      let tempCart = cart[i];
      let itemPrice = tempCart.price * 100 * tempCart.num;
      tempCart.totalPrice = itemPrice / 100;
      totalPrice += itemPrice / 100;
    }
    that.setData({
      queryType: queryType,
      merchantId: merchantId,
      peopleNum: jsonData.peopleNum,
      inHallPreMenu: inHallPreMenu,
      //orderType: orderType,
      itemInfoList: cart,
      totalPrice: totalPrice * 100
    })

    

    if (queryType == 0) {
      // 计算总金额
      /*let totalPrice = 0
      for (var i = 0; i < cart.length; i++) {
        let tempCart = cart[i];
        let itemPrice = tempCart.price * 100 * tempCart.num;
        tempCart.totalPrice = itemPrice / 100;
        totalPrice += itemPrice / 100;
      }*/
      /*wx.request({
        url: url + '/OrderApi/queryEatServiceByMerchant',
        data: {
          merchantId: merchantId,
          orderType: orderType
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          if (res.data.code == 200) {
            let eatService = res.data.data;
            console.log(eatService);
            let tempTitle = "";
            orderType = eatService.orderType;
            if (orderType == 'SUBSCRIBE_IN_HALL') {
              tempTitle = "(预约餐桌)"
              // 如果是预约餐桌，且非到店点餐时候，需加上茶位费
              if(inHallPreMenu == 1){
                let peopleNum = jsonData.peopleNum;
                let tableFee = eatService.tableFeePerPerson;
                let totalTableFee = peopleNum * tableFee * 100;
                that.setData({
                  tableFee: tableFee,
                  totalTableFee: totalTableFee / 100
                })
                totalPrice += totalTableFee / 100;
                // 如果定金字段不为 0 ，则该笔订单只需支付对应的定金比例的钱
                if(eatService.depositRate != 0){
                  that.setData({
                    depositRate: eatService.depositRate
                  })
                  let rate = eatService.depositRate / 100;
                  totalPrice = totalPrice * 100 * rate;
                  totalPrice = totalPrice / 100;
                }
              }
            } else if (orderType == 'PICK_UP') {
              tempTitle = "(自提)"
            } else if (orderType == 'TAKE_OUT') {
              tempTitle = "(商家配送)"
            } else if (orderType == 'IN_HALL') {
              tempTitle = "(堂食)"
            }
            console.log(totalPrice);
            that.setData({
              time: jsonData.timeVal,
              deskInfo: jsonData.deskVo,
              itemInfoList: cart,
              totalPrice: totalPrice * 100,
              orderType: jsonData.orderType,
              payonline: eatService.payonline
            });
            let orderType = jsonData.orderType;
            wx.setNavigationBarTitle({
              title: "我的订单" + tempTitle
            })

          } else if (queryType == 1) {
            wx.setNavigationBarTitle({
              title: "我的订单"
            })
            let totalPrice = 0
            let differDay = jsonData.differDay;
            for (var i = 0; i < cart.length; i++) {
              let tempCart = cart[i];
              let itemPrice = tempCart.value * 100 * tempCart.num * differDay;
              tempCart.totalPrice = itemPrice / 100;
              totalPrice += itemPrice / 100;
            }
            that.setData({
              time: jsonData.startTime + " 至 " + jsonData.endTime + " , 共 " + differDay + " 晚",
              itemInfoList: cart,
              totalPrice: totalPrice * 100,
              differDay: differDay
            });

          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000
            })
          }
        },
        fail: function (res) {
          console.info('submit fail');
        },
        complete: function (res) {
          console.info('submit complete');
        }
      })*/
    } else if (queryType == 2) {
      wx.setNavigationBarTitle({
        title: "我的订单"
      })
      let totalPrice = 0
      let selectCart = [];
      for (var i = 0; i < cart.length; i++) {
        let tempCart = cart[i];
        if (tempCart.num != 0) {
          let itemPrice;
          if (tempCart.payType == 0) {
            itemPrice = tempCart.originalPrice * 100 * tempCart.num;
          } else {
            itemPrice = tempCart.discountPrice * 100 * tempCart.num;
          }
          tempCart.totalPrice = itemPrice / 100;
          totalPrice += itemPrice / 100;
          selectCart.push(tempCart);
        }
      }
      let dateValue = jsonData.dateValue;
      console.log("222 : " + selectCart);
      that.setData({
        time: dateValue,
        itemInfoList: selectCart,
        totalPrice: totalPrice * 100,
      });
    }
  },
  popupDate: function () {
    this.setData({
      showDate: true
    });
  },
  popupTime: function () {
    this.setData({
      showTime: true
    });
  },
  onConfirm(e) {
    this.setData({
      showDate: false
    });
    this.setData({
      currentDate: e.detail,
      displayDate: util.formatDate(e.detail)
    });
  },
  onCancel() {
    this.setData({
      showDate: false
    });
  },
  closePrePop: function () {
    let _that = this;
    _that.setData({
      takeOutPopupShow: false,
    })
  },
  onConfirmTakeOutInfo: function(){
    let _that = this;
    _that.setData({
      takeOutPopupShow: false,
      takeOutDateTime: _that.data.displayDate + " " + _that.data.displayTime
      
    })
  },
  onInput(event) {
    //获取操作改变的值
    //this.setData({
    //currentDate: event.detail
    //});
  },
  onConfirmTime(e) {
    this.setData({
      showTime: false
    });
    this.setData({
      //currentDate: e.detail,
      displayTime: e.detail
    });
  },
  onCancelTime() {
    this.setData({
      showTime: false
    });
  },
  //默认堂食 点击堂食
  clickInHall: function(){
    var that = this;
    that.setData({
      inHallDot : true,
      takeOutDot : false,
      takeOutInfoShow: false,
      orderType: 'IN_HALL'
    })
  },
  //点击自提
  clickTakeOut: function(){
    var that = this;
    that.setData({
      takeOutDot: true,
      inHallDot : false,
      takeOutPopupShow : true,
      takeOutInfoShow: true,
      orderType: 'PICK_UP'
    })
  },
  /**
   * 退订
   */
  unSubscribeOrder: function (option) {
    Dialog.confirm({
      message: '是否需要退订？'
    }).then(() => {
      // 确定退订
      var that = this;
      wx.request({
        url: url + '/OrderApi/unSubscribeOrderByOrderId',
        data: {
          orderId: that.data.orderId
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          console.log(res);
          if (res.data.code == 200) {
            Toast.success('退订成功!');
            wx.switchTab({
              url: '../../pages/index/index'
            });
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000
            })
          }
        },
        fail: function (res) {
          console.info('submit fail');
        },
        complete: function (res) {
          console.info('submit complete');
        }
      })
    }).catch(() => {
      // on cancel
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _that = this;
    _that.setData({
      disabledStatus: false
    })
    let orderType = _that.data.orderType;
    wx.getStorage({
      key: "openId",
      success(res) {
        _that.setData({
          uuid: res.data
        })
        //if (orderType != 'IN_HALL') {
        
        if (_that.data.isShareByJielong == "N"){
          wx.request({
            url: url + '/CommonRelationApi/queryCommonRelationByUuid',
            data: {
              uuid: res.data
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              console.log(res);
              if (res.data.code == 200) {
                let item = res.data.data;
                _that.setData({
                  relationName: item.name,
                  relationPhone: item.phone
                })
              } else if (res.data.code == 500) {
                // 尚未登录
                Dialog.confirm({
                  title: '提示',
                  message: '您当前尚未登录, 请点击确认跳转登录页面!'
                }).then(() => {
                  // on confirm
                  wx.navigateTo({
                    url: "../../pages/login/index"
                  })
                }).catch(() => {
                  // on cancel
                });
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: "none",
                  duration: 2000
                })
                _that.setData({
                  relationName: '',
                  relationPhone: ''
                })
              }
            },
            fail: function (res) {
              console.info('submit fail');
            },
            complete: function (res) {
              console.info('submit complete');
            }
          })
        }

      },
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})